package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.article.client.ArticleFeign;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.AuthorDto;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.dtos.UserAuthDto;
import com.usian.user.entity.ApUser;
import com.usian.user.entity.ApUserAuth;
import com.usian.user.mapper.ApUserAuthMapper;
import com.usian.user.service.IApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.user.service.IApUserService;
import com.usian.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-09-29
 */
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements IApUserAuthService {

    @Override
    public PageResult<UserAuthDto> findPage(AuthDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、封装分页条件和查询条件
        Page<ApUserAuth> page = new Page<>(dto.getPage(),dto.getSize());
        Integer status = dto.getStatus();
        QueryWrapper<ApUserAuth> queryWrapper = new QueryWrapper<>();
        if(status!=null){
            queryWrapper.lambda().eq(ApUserAuth::getStatus,status);
        }
        //3、执行查询
        IPage<ApUserAuth> iPage = this.page(page, queryWrapper);
        //4、封装查询结果
        List<ApUserAuth> records = iPage.getRecords();
        if(CollectionUtils.isEmpty(records)){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<UserAuthDto> authDtoList = BeanHelper.copyWithCollection(records, UserAuthDto.class);

        return new PageResult<>(dto.getPage(),dto.getSize(),iPage.getTotal(),authDtoList);
    }

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserService apUserService;

    @Override
    @GlobalTransactional //开启全局事务管理
    public void updateAuthStatus(AuthDto dto, Integer status) {
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if(status!=9 && status!=2){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1、更新用户审核状态
        ApUserAuth apUserAuth = BeanHelper.copyProperties(dto, ApUserAuth.class);
        apUserAuth.setStatus(status);
        apUserAuth.setReason(dto.getMsg());//审核失败的原因
        this.updateById(apUserAuth);
        //获取认证信息
        ApUserAuth userAuth = this.getById(dto.getId());
        if(userAuth==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询App用户信息
        ApUser apUser = apUserService.getById(userAuth.getUserId());
        Integer apUserId = apUser.getId();
        //2、审核通过，需要创建自媒体用户和作者信息
        if(status==9){
            //保存自媒体用户
            try {
                WmUserDto wmUserDto = new WmUserDto();
                wmUserDto.setPhone(apUser.getPhone());
                wmUserDto.setName(apUser.getName());
                wmUserDto.setImage(apUser.getImage());
                wmUserDto.setPassword(apUser.getPassword());
                wmUserDto.setApUserId(apUserId);
                wmUserDto.setStatus(status);
                Integer wmUserId = wemediaFeign.save(wmUserDto);
                //保存文章作者
                AuthorDto authorDto = new AuthorDto();
                authorDto.setUserId(apUserId);
                authorDto.setName(apUser.getName());
                authorDto.setType(2);
                authorDto.setWmUserId(wmUserId);//关联自媒体用户
                articleFeign.save(authorDto);

                //更新App用户标识为“自媒体人”
                ApUser apUser1 = new ApUser();
                apUser1.setId(apUserId);
                apUser1.setFlag(1);
                apUserService.updateById(apUser1);

            } catch (Exception e) {
                e.printStackTrace();
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存自媒体用户或作者信息失败");
            }
        }
        //int i=1/0;
    }
}
